package com.qf.servlet;

import com.qf.Utils.DaoUtils;
import com.qf.entity.Admin;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

//获得用户头像
@WebServlet(urlPatterns = "/getUserImg")
public class GetUserImgServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //直接在session中获取当前用户的头像名称
        Admin admin = (Admin) req.getSession().getAttribute("user_login");
        System.out.println(admin);


        if (admin == null) {
            resp.sendRedirect("login.jsp");
            return;
        }
        String header = admin.getHeader();
        System.out.println("------>获取用户头像的名称：" + header);

        //用默认头像
        if (header==null || header == "") {
            System.out.println("头像回显完成");
            //头像的File对象
            File file = new File(DaoUtils.file + "ac8754f7-4e3e-4c7e-ba41-bd2c62851a6a");
            try (
                    InputStream in = new FileInputStream(file);
                    OutputStream out = resp.getOutputStream();
            ) {
                IOUtils.copy(in, out);
            }

            return;
        }

        //用户头像
        //头像的File对象

        File file = new File(DaoUtils.file + header);
        try (
                InputStream in = new FileInputStream(file);
                OutputStream out = resp.getOutputStream();
        ) {
            IOUtils.copy(in, out);

        }


    }
}
